package com.laicunba.ext.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.laicunba.constant.AttributeConstant;
import com.laicunba.constant.GloabConstant;
import com.laicunba.ext.web.init.CookieUtil;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.SessionUtil;
import com.laicunba.util.StringUtil; 

public class ConsoleNoLoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		/**
		 * 如果是debug模式,则不需要登录
		 */
		if (GloabConstant.DEBUG) {
			try {
				SessionUtil.CURRENT_USER_ID.set(GloabConstant.ROOT_USER_ID_AND_NAME);
				chain.doFilter(request, res);
			} finally {
				SessionUtil.CURRENT_USER_ID.remove();
			}
			return;
		}

		/**
		 * 正常拦截
		 */
		String managerUserId = null;
		String token = CookieUtil.get((HttpServletRequest) request, "admin_login_token");
		if (StringUtil.isNotEmpty(token)) {
			managerUserId = CacheUtil.getAttribute(AttributeConstant.ADMIN_LOGIN_TOKEN + token);
		}
		if (StringUtil.isEmpty(managerUserId)) {
			HttpServletResponse response = (HttpServletResponse) res;
			response.sendRedirect(GloabConstant.WEB_PATH + "/login.jsp");
			return;
		}
		try {
			SessionUtil.CURRENT_USER_ID.set(managerUserId);
			chain.doFilter(request, res);
		} finally {
			SessionUtil.CURRENT_USER_ID.remove();
		}

	}

	@Override
	public void destroy() {

	}

}
